<?php

namespace App\Server\Admin;

use Illuminate\Support\Facades\Auth;

class User
{
    private $userModel;

    public function __construct()
    {
        $this->userModel = new \App\Models\User;
    }

    public function register()
    {
        return $this->userModel->adminRegister([
            'u_name' => Request()->name,
            'u_role' => 'admin',
            'u_password' => \App\Server\Util::getUserPassword(Request()->password),
            'u_password_text' => Request()->password,
            'u_level' => 1,
            'u_ip' => \App\Server\Util::ipGet(),
            'openid' => '', 
        ]);
    }

    public function login()
    {
        return array_merge([
            'token' => $this->userJwtAuth(),
        ], $this->loginResponseGet());
    }

    private function userJwtAuth()
    {
        $token = Auth::attempt([
            'u_name' => Request()->name,
            'password' => \App\Server\Util::saltPwd(Request()->password),
        ]);
        if(empty($token)){
            throw new \Exception(json_encode(['error', ...config('api.error.jwtAuthErr')]));
        }
        return $token;
    }

    private function loginResponseGet()
    {
        return [
            'desc' => 'manager',
            'uesrId' => Request()->user()->u_id,
            'username' => Request()->user()->u_name,
            'realName' => Request()->user()->u_name,
            'role' => [
                'roleName' => 'Super Admin',
                'value' => 'super',
            ],
        ];
    }

    public function userInfoGet()
    {
        return [
            'homePath' => '/store',
            'avatar' => Request()->user()->u_avatar,
            'realName' => Request()->user()->u_name,
        ];
    }

    public function logout()
    {
        return auth()->logout(true);
    }
}